import React from 'react';
import language from 'antd/locale/zh_CN';
import { InjectContext } from '~/enumerate/context';
import { App, ConfigProvider, theme as antdTheme } from 'antd';

export default class Container extends React.Component {
  state = window?.base?.themeConfig || {
    algorithm: process.env.app.antd[ 'algorithm' ],
    borderRadius: process.env.app.antd[ 'borderRadius' ],
    colorPrimary: process.env.app.antd[ 'colorPrimary' ]
  };

  get token () {
    const {
      colorPrimary,
      borderRadius
    } = this.state;
    return {
      fontFamily: process.env.app.antd[ 'fontFamily' ],
      colorPrimary,
      borderRadius
    };
  }

  get algorithm () {
    return antdTheme[ this.state.algorithm ];
  }

  componentDidMount () {
    if (window.__IN_BASE__) {
      window.base.addEventListener('EVENT_THEME_CONTROL', e => {
        const config = e.data;
        this.setState({ [ config.field ]: config.value });
      });
    }
  }

  render () {
    return (
      <ConfigProvider
        theme={{
          token: this.token,
          algorithm: this.algorithm
        }}
        locale={language}
        prefixCls={process.env.app.antd[ 'ant-prefix' ]}
      >
        <App style={{ height: '100%' }}>
          <AppMiddle {...this.props} />
        </App>
      </ConfigProvider>
    );
  }
}

function AppMiddle (props) {
  return (
    <InjectContext.Provider value={App.useApp()}>
      {props.children}
    </InjectContext.Provider>
  );
}
